package com.LachesismStorm.lachesism.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Author lachesism
 * @Date 2023-07-07 10:57
 **/
@Component
@ServerEndpoint("/chat")
public class ChatWebSocketService {
    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        broadcast("用户 " + session.getId() + " 加入了聊天",null);
    }
    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        broadcast("用户 " + session.getId() + " 离开了聊天",null);
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        broadcast("用户 " + session.getId() + ": " + message,session.getId());
    }
    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("Error in session " + session.getId());
        error.printStackTrace();
    }
    private void broadcast(String message,String id) {
        for (Session session : sessionMap.values()) {
            if (id == null || session.getId() != id){
                session.getAsyncRemote().sendText(message);
            }
        }
    }
}